package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.MenuTypeEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FileImportExportHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.service.TemplateService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigFindDTO;
import com.xbongbong.pro.companyconfig.pojo.vo.CompanyConfigFindVO;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.PackageConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.AppStoreErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.packages.enums.FeaturesEnum;
import com.xbongbong.pro.template.pojo.CompanyPojo;
import com.xbongbong.pro.template.pojo.EnablePojo;
import com.xbongbong.pro.template.pojo.TemplateMenuPojo;
import com.xbongbong.pro.template.pojo.TemplatePojo;
import com.xbongbong.pro.template.pojo.dto.CompanySaveDTO;
import com.xbongbong.pro.template.pojo.dto.ListTemplateSortDTO;
import com.xbongbong.pro.template.pojo.dto.TemplateChangeDTO;
import com.xbongbong.pro.template.pojo.dto.TemplateDTO;
import com.xbongbong.pro.template.pojo.dto.TemplatePermissionDTO;
import com.xbongbong.pro.template.pojo.dto.TemplatePermissionSetDTO;
import com.xbongbong.pro.template.pojo.vo.CompanyVO;
import com.xbongbong.pro.template.pojo.vo.EnableVO;
import com.xbongbong.pro.template.pojo.vo.GroupMenuVO;
import com.xbongbong.pro.template.pojo.vo.TemplateGroupMenuVO;
import com.xbongbong.pro.template.pojo.vo.TemplateListVO;
import com.xbongbong.pro.template.pojo.vo.TemplateMenuVO;
import com.xbongbong.pro.template.pojo.vo.TemplatePermissionVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.FormTypeEnum;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SaasMenuEnum;
import com.xbongbong.saas.enums.TemplateCompanyConfigEnum;
import com.xbongbong.saas.enums.TemplateConfigGroupEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.help.FieldAttrHelp;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.model.FormTemplateModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.impl.FormTemplateModelImpl;
import com.xbongbong.saas.service.WorkOrderFormService;
import com.xbongbong.saas.service.toolbox.help.UpdatePackageRedisService;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/1/29 15:14
 * @since v1.0
 */
@Service("templateService")
public class TemplateServiceImpl implements TemplateService {
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private UpdatePackageRedisService updatePackageRedisService;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private FieldAttrHelp fieldAttrHelp;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private WorkOrderFormService workOrderFormService;
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PaasAppService paasAppService;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private FormTemplateModel formTemplateModel;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    @Lazy
    private FileImportExportHelp fileImportExportHelp;

    private static final Logger LOG = LoggerFactory.getLogger(PaasFormDataServiceImpl.class);

    @Override
    public TemplateMenuVO getMenuList(TemplateDTO templateDTO) throws XbbException {
        String corpid = templateDTO.getCorpid();
        PaasAppEntity paasAppEntity = paasAppModel.getByKey(templateDTO.getAppId(), corpid);
        if (paasAppEntity == null) {
            throw new XbbException(AppStoreErrorCodeEnum.API_ERROR_300001);
        }
        String paasAppAlias = paasAppEntity.getAlias();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",DelEnum.NORMAL.getDel());
        map.put("appId",templateDTO.getAppId());
        map.put("negAliasIn",Arrays.asList(XbbRefTypeEnum.WORK_REPORT.getAlias()));
        List<PaasMenuEntity> paasMenuEntityList = paasMenuModel.list(map);
        // 删掉没有解释的菜单
        List<PaasFormExplainEntity> paasFormExplainList = paasFormExplainModel.list(map);
        Map<Long, PaasFormExplainEntity> menuIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paasFormExplainList.forEach(item -> menuIdMap.put(item.getMenuId(), item));
        if (!Objects.equals(paasAppAlias, XbbRefTypeEnum.JXC.getAlias())) {
            // 竞争对手的没有解释的，需要特殊处理，不过滤
            paasMenuEntityList.removeIf(paasMenuEntity -> !Objects.equals(XbbRefTypeEnum.COMPETITOR.getAlias(), paasMenuEntity.getAlias()) &&!menuIdMap.containsKey(paasMenuEntity.getId()));
        } else {
            paasMenuEntityList.removeIf(paasMenuEntity -> !Objects.equals(MenuTypeEnum.GROUP.getType(), paasMenuEntity.getType()) && Objects.equals(paasMenuEntity.getSaasMark(), 2) && !menuIdMap.containsKey(paasMenuEntity.getId()));
        }
        Integer saasMark = paasAppEntity.getSaasMark();
        if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
            //根据套餐获取当前公司套餐不能看到的菜单
            List<String> unSeeMenuList = packageHelp.getUnSeeMenuList(corpid);
            paasMenuEntityList.removeIf(paasMenuEntity -> unSeeMenuList.contains(paasMenuEntity.getAlias()));
        }
        List<TemplateMenuPojo> templateMenuPojoList = new ArrayList<>();
        Map<Long, List<TemplateMenuPojo>> menuMap = new HashMap<>(paasMenuEntityList.size());
        boolean isWorkOrderUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.WORK_ORDER.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
        for (PaasMenuEntity entity : paasMenuEntityList){
            String alias = entity.getAlias();
            Long parentId = entity.getParentId();
            // 多模板标识转换
            Integer distributorMark = entity.getDistributorMark();
            Integer menubusinessType = XbbRefTypeEnum.getByAlias(alias).getCode();
            //预收款列表不提供表单设计
            boolean noFormDesignFlag = Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(),menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(),menubusinessType)
                    || (!isWorkOrderUse && Objects.equals(alias, XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getAlias())
                    || Objects.equals(XbbRefTypeEnum.BATCH_FLOW_BILL.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.SEQ_SEARCH.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode(), menubusinessType))
                    || Objects.equals(XbbRefTypeEnum.ONLINE_PAYMENT_FLOW.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.CREDIT_LIMIT.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.CREDIT_CARD_BILL.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.WAIT_PURCHASE.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.SMART_REPLENISHMENT.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.WAIT_OUTSTOCK.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode(), menubusinessType )
                    || Objects.equals(XbbRefTypeEnum.SLA_LOG.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_APPOINT.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_POOL.getCode(), menubusinessType)
                    || Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2.getCode(), menubusinessType);
            if(noFormDesignFlag){
                continue;
            }
            SaasMenuEnum saasMenuEnum = SaasMenuEnum.getBySubType(menubusinessType);
            Boolean compayConfig = saasMenuEnum == null ? false : saasMenuEnum.getCompanyConfig();
            TemplateMenuPojo templateMenuPojo = new TemplateMenuPojo();
            templateMenuPojo.setAlias(alias);
            if (Objects.equals(menubusinessType, XbbRefTypeEnum.UNKNOWN.getCode())) {
                menubusinessType = 0;
            }
            templateMenuPojo.setSaasMark(entity.getSaasMark());
            templateMenuPojo.setBusinessType(menubusinessType);
            templateMenuPojo.setMenuName(entity.getName());
            templateMenuPojo.setMenuNameEn(entity.getNameEn());
            templateMenuPojo.setCompanyConfig(compayConfig);
            templateMenuPojo.setMenuId(entity.getId());
            templateMenuPojo.setIsMulti(RedundantTemplateTypeEnum.isMultiTemplate(XbbRefTypeEnum.transferBusinessType4Distributor(menubusinessType, distributorMark)));
            templateMenuPojo.setId(entity.getId());
            templateMenuPojo.setType(entity.getType());
            templateMenuPojo.setParentId(entity.getParentId());

            if (Objects.equals(paasAppAlias, XbbRefTypeEnum.DISTRIBUTOR.getAlias()) || Objects.equals(paasAppAlias, XbbRefTypeEnum.ORDER_CENTER.getAlias())) {
                templateMenuPojo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
            }
            // 去掉账号管理的表单设计页
            if (Objects.equals(alias, XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getAlias())) {
                continue;
            }

            // 表单模版进销存分组
            if (Objects.equals(paasAppAlias, XbbRefTypeEnum.JXC.getAlias())) {
                // 库存查询和模拟生产没有表单模版
                if(Objects.equals(XbbRefTypeEnum.STOCK_SEARCH.getAlias(), alias) ||  Objects.equals(XbbRefTypeEnum.SIMULATED_PRODUCTION.getAlias(), alias)
                    || Objects.equals(XbbRefTypeEnum.STOCK_FLOW_BILL.getAlias(), alias) ||  Objects.equals(XbbRefTypeEnum.STOCK_STANDING_BOOK.getAlias(), alias)){
                    continue;
                }
                // parentId = 0 为父级菜单
                if (Objects.equals(parentId, 0L)) {
                    // 存放一级菜单
                    templateMenuPojoList.add(templateMenuPojo);
                } else {
                    // 获取二级菜单，并放到容器中
                    if (Objects.isNull(menuMap.get(parentId))) {
                        List<TemplateMenuPojo> paasMenuList = new ArrayList<>();
                        paasMenuList.add(templateMenuPojo);
                        menuMap.put(entity.getParentId(), paasMenuList);
                    } else {
                        List<TemplateMenuPojo> paasMenuList = menuMap.get(parentId);
                        paasMenuList.add(templateMenuPojo);
                        menuMap.put(entity.getParentId(), paasMenuList);
                    }
                }
            } else {
                templateMenuPojoList.add(templateMenuPojo);
            }
        }

        // 表单模版进销存分组
        if (Objects.equals(paasAppAlias, XbbRefTypeEnum.JXC.getAlias())) {
            // 分组下没有子菜单，直接删除
            Iterator<TemplateMenuPojo> iterator = templateMenuPojoList.iterator();
            while(iterator.hasNext()){
                TemplateMenuPojo item = iterator.next();
                if(Objects.nonNull(menuMap.get(item.getId())) && !menuMap.get(item.getId()).isEmpty()){
                    // 将子菜单放入父菜单
                    item.setSubMenuList(menuMap.get(item.getId()));
                } else if(Objects.equals(item.getType(), MenuTypeEnum.GROUP.getType())
                        && (Objects.isNull(menuMap.get(item.getId())) || menuMap.get(item.getId()).isEmpty())){
                    iterator.remove();
                    continue;
                }
            }
        }

        TemplateMenuVO templateMenuVO = new TemplateMenuVO();

        templateMenuVO.setMenuList(templateMenuPojoList);
        // 国际化白名单
        CompanyConfigEntity entity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.I18N_WHITE.getAlias(), PaasConstant.DEFAULT_DATA_CORPID);
        String value = CompanyConfigEnum.I18N_WHITE.getValue();
        if (Objects.nonNull(entity)) {
            value = entity.getConfigValue();
        }
        List<String> whiteList = JsonHelperUtil.parseArray(value, String.class);
        boolean flag = CollectionsUtil.isNotEmpty(whiteList) && whiteList.contains(corpid);
        templateMenuVO.setMultiLang(flag);
        return templateMenuVO;
    }

    /**
     * 表单设置 获取saas应用下的分组菜单列表
     *
     * @param templateDTO 参数
     * @return 菜单列表
     * @throws XbbException XbbException
     * @author youli.chen
     */
    @Override
    public TemplateGroupMenuVO getMenuGroup(TemplateDTO templateDTO) throws XbbException {
        TemplateGroupMenuVO templateGroupMenuVO = new TemplateGroupMenuVO();

        String corpid = templateDTO.getCorpid();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("enable", BasicConstant.ONE);
        map.put("orderByStr", "sort ASC");
        map.put("del",DelEnum.NORMAL.getDel());
        map.put("appId",templateDTO.getAppId());
        map.put("typeIn", Arrays.asList(0, 1, 2, 3, 4));
        map.put("negAliasIn",Arrays.asList(XbbRefTypeEnum.WORK_REPORT.getAlias()));
        List<PaasMenuEntity> paasMenuEntityList = paasMenuModel.list(map);

        // 获取菜单列表
        List<GroupMenuVO> menuExtList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<GroupMenuVO>> menuMap = new HashMap<>(paasMenuEntityList.size());
        boolean isWorkOrderUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.WORK_ORDER.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
        for (PaasMenuEntity entity : paasMenuEntityList){
            Long parentId = entity.getParentId();
            String alias = entity.getAlias();
            Integer menubusinessType = XbbRefTypeEnum.getByAlias(alias).getCode();
            //预收款列表不提供表单设计
            boolean noFormDesignFlag = Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(),menubusinessType) ||  (!isWorkOrderUse && Objects.equals(alias, XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getAlias())) || Objects.equals(XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode(), menubusinessType);
            if(noFormDesignFlag){
                continue;
            }
            SaasMenuEnum saasMenuEnum = SaasMenuEnum.getBySubType(menubusinessType);
            Boolean compayConfig = saasMenuEnum == null ? false : saasMenuEnum.getCompanyConfig();
            if (Objects.equals(menubusinessType, XbbRefTypeEnum.UNKNOWN.getCode())) {
                menubusinessType = 0;
            }
            GroupMenuVO groupMenuVO = new GroupMenuVO();
            groupMenuVO.setId(entity.getId());
            groupMenuVO.setSaasMark(entity.getSaasMark());
            groupMenuVO.setBusinessType(menubusinessType);
            groupMenuVO.setMenuName(entity.getName());
            groupMenuVO.setCompanyConfig(compayConfig);
            groupMenuVO.setMenuId(entity.getId());
            groupMenuVO.setType(entity.getType());
            groupMenuVO.setParentId(entity.getParentId());
            groupMenuVO.setIsMulti(RedundantTemplateTypeEnum.isMultiTemplate(menubusinessType));

            // parentId = 0 为父级菜单
            if (Objects.equals(parentId, 0L)) {
                // 存放一级菜单
                menuExtList.add(groupMenuVO);
            } else {
                // 获取二级菜单，并放到容器中
                if (Objects.isNull(menuMap.get(entity.getParentId()))) {
                    List<GroupMenuVO> paasMenuList = new ArrayList<>();
                    paasMenuList.add(groupMenuVO);
                    menuMap.put(entity.getParentId(), paasMenuList);
                } else {
                    List<GroupMenuVO> paasMenuList = menuMap.get(entity.getParentId());
                    paasMenuList.add(groupMenuVO);
                    menuMap.put(entity.getParentId(), paasMenuList);
                }
            }
        }

        // 分组下没有子菜单，直接删除
        Iterator<GroupMenuVO> iterator = menuExtList.iterator();
        while(iterator.hasNext()){
            GroupMenuVO item = iterator.next();
            if((Objects.isNull(menuMap.get(item.getId())) || menuMap.get(item.getId()).isEmpty())){
                iterator.remove();
                continue;
            }
        }
        templateGroupMenuVO.setMenuList(menuExtList);
        return templateGroupMenuVO;
    }


    @Override
    public TemplateListVO getFormList(TemplateDTO templateDTO) throws XbbException {
        String corpid = templateDTO.getCorpid();
        Map<String,Object> map = BeanUtil.convertBean2Map(templateDTO,true);
        map.put("del",0);
        //根据PrintFlag判断是否是新建打印的调用。如果是打印那边的请求，那么只展示“启用的”和“有使用权限”的表单
        boolean isPrintFlag = new Integer(1).equals(templateDTO.getPrintFlag());
        if(isPrintFlag){
            map.put("enable",1);
        }
        List<String> featureList = packageHelp.getFeatureList(corpid);
        map.put("hidden", 0);
        List<PaasFormEntityExt> paasFormEntityList = paasFormModel.list(map);
        TemplateListVO templateListVO = new TemplateListVO();
        List<TemplatePojo> templatePojoList = new ArrayList<>();
        Integer saasMark = null;
        if (CollectionsUtil.isNotEmpty(paasFormEntityList)) {
            Long appId = paasFormEntityList.get(0).getAppId();
            PaasAppEntity appEntity = paasAppModel.getByKey(appId, corpid);
            if (Objects.isNull(appEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_EXIST);
            }
        }
        for (PaasFormEntityExt paasFormEntityExt : paasFormEntityList){
            TemplatePojo templatePojo = new TemplatePojo();
            templatePojo.setFormId(paasFormEntityExt.getId());
            templatePojo.setFormName(paasFormEntityExt.getName());
            templatePojo.setFormNameEn(paasFormEntityExt.getNameEn());
            List<OptionalRangeEntity> permissions = getPermissions(paasFormEntityExt);
            if(isPrintFlag) {
                //过滤掉当前用户没有使用权限的用户,true表示没权限
                Boolean noPermission = CollectionsUtil.isNotEmpty(permissions) && paasFormHelp.haveNoPermission(templateDTO.getLoginUser(), permissions);
                if (Objects.equals(paasFormEntityExt.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && RedundantTemplateTypeEnum.isMultiTemplate(paasFormEntityExt.getBusinessType()) && noPermission) {
                    continue;
                }
            }
            if (!featureList.contains(FeaturesEnum.APPLICATION.getAlias()) && Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
                templatePojo.setPackageLimit(1);
            }
            templatePojo.setPermissions(permissions);
            templatePojo.setPermission(getPermission(permissions));
            templatePojo.setOperatorList(getOperatorList(paasFormEntityExt));
            templatePojo.setEnable(Objects.equals(paasFormEntityExt.getEnable(),1));
            templatePojo.setBusinessType(paasFormEntityExt.getBusinessType());
            templatePojo.setMenuId(paasFormEntityExt.getMenuId());
            templatePojo.setDistributorMark(paasFormEntityExt.getDistributorMark());
            templatePojoList.add(templatePojo);
        }
        templateListVO.setFormList(templatePojoList);
        //是否是普通多模板
        boolean isMultiTemplate = FormTypeEnum.isMultiTemplate(XbbRefTypeEnum.transferBusinessType4Distributor(templateDTO.getBusinessType(), templateDTO.getDistributorMark()));
        /**
         是否是特殊多模板，且已经存在了多个模板（有可能还未初始化经销商相关模板，还是原有单模板）
         特殊多模板出现多个form时，展现形式为多模板，但是：无新建模板按钮，不允许启用关闭模板，无法设置使用权限
         */
        boolean isMultiSingleTemplate = FormTypeEnum.isMultiSingleTemplate(templateDTO.getBusinessType()) && templatePojoList.size() > BasicConstant.ONE;
        templateListVO.setFormType(isMultiTemplate || isMultiSingleTemplate? FormTypeEnum.MULTI_TEMPLATE.getFormType(): FormTypeEnum.SINGLE_TEMPLATE.getFormType());
        //为特殊多模板业务，且已经存在了多个模板
        templateListVO.setOperateFlag(isMultiSingleTemplate ? BasicConstant.ZERO : BasicConstant.ONE);
        templateListVO.setFormTitle("");
        // 国际化白名单
        CompanyConfigEntity entity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.I18N_WHITE.getAlias(), PaasConstant.DEFAULT_DATA_CORPID);
        String value = CompanyConfigEnum.I18N_WHITE.getValue();
        if (Objects.nonNull(entity)) {
            value = entity.getConfigValue();
        }
        Integer num = updatePackageRedisService.getUnusedNumPackageLimit(corpid, ValueAddedTypeEnum.CUSTOM_FORM_NUM);

        if (num > 0) {
            // 没有自定义表单的
            templateListVO.setPackageLimit(1);
            templateListVO.setMessage(String.format(I18nMessageUtil.getMessage(PackageConstant.CUSTOM_FORM_SIZE_MESSAGE), num));
            if (templateDTO.getLoginUser().isAdmin()) {
                templateListVO.setUpgrade(1);
            }
        }
        List<String> whiteList = JsonHelperUtil.parseArray(value, String.class);
        boolean flag = CollectionsUtil.isNotEmpty(whiteList) && whiteList.contains(templateDTO.getCorpid());
        templateListVO.setMultiLang(flag);
        return templateListVO;
    }

    /**
     * 获取可以删除的操作列表
     * @param paasFormEntityExt
     * @return
     */
    public List<ButtonPojo> getOperatorList(PaasFormEntityExt paasFormEntityExt) {
        List<ButtonPojo> operatorList = new ArrayList<>();
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), paasFormEntityExt.getSaasMark())) {
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(XbbRefTypeEnum.transferBusinessType4Distributor(paasFormEntityExt.getBusinessType(), paasFormEntityExt.getDistributorMark()));
            switch (xbbRefTypeEnum) {
                case CUSTOMER_MANAGEMENT:
                case CONTRACT:
                case RECEIPT_ORDER:
                case SALES_OPPORTUNITY:
                case CLUE:
                    ButtonPojo buttonPojo = new ButtonPojo();
                    buttonPojo.setAttr(OperateTypeEnum.DELETE.getAlias());
                    buttonPojo.setType(OperateTypeEnum.DELETE.getAlias());
                    buttonPojo.setValue(OperateTypeEnum.DELETE.getName());
                    operatorList.add(buttonPojo);
                    break;
                default:
                    break;
            }
        } else {
            ButtonPojo buttonPojo = new ButtonPojo();
            buttonPojo.setAttr(OperateTypeEnum.DELETE.getAlias());
            buttonPojo.setType(OperateTypeEnum.DELETE.getAlias());
            buttonPojo.setValue(OperateTypeEnum.DELETE.getName());
            operatorList.add(buttonPojo);
        }
        return operatorList;
    }


    /**
     * 获取使用权限列表
     * @param paasFormEntityExt
     * @return
     * 创建时间 2019/6/8 2:00 PM
     * 修改时间 2019/6/8 2:00 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private List<OptionalRangeEntity> getPermissions(PaasFormEntityExt paasFormEntityExt) {
        String permissionStr = paasFormEntityExt.getPermission();
        List<OptionalRangeEntity> permissions = null;

        try {
            permissions = JSON.parseArray(permissionStr, OptionalRangeEntity.class);
        } catch (Exception e) {

        }

        if (permissions == null) {
            permissions = new ArrayList<>();
        }
        return permissions;
    }

    /**
     * 拼接使用权限回显
     * @param permissions
     * @return
     * 创建时间 2019/6/8 2:01 PM
     * 修改时间 2019/6/8 2:01 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private String getPermission(List<OptionalRangeEntity> permissions) {

        if (permissions == null || permissions.isEmpty()) {
            return I18nMessageUtil.getMessage(I18nStringConstant.NOT_LIMIT);
        }
        StringBuilder permission = new StringBuilder();
        for (OptionalRangeEntity optionalRangeEntity : permissions) {
            if (StringUtil.isEmpty(permission.toString())) {
                permission.append(optionalRangeEntity.getName());
            } else {
                permission.append("，" + optionalRangeEntity.getName());
            }

        }
        return permission.toString();
    }

    @Override
    public TemplatePermissionVO getTemplatePermission(TemplatePermissionDTO templatePermissionDTO) throws XbbException {
        String corpid = templatePermissionDTO.getCorpid();
        Long formId = templatePermissionDTO.getFormId();
        PaasFormEntityExt paasForm = paasFormModel.getByKey(formId, corpid);

        String permission = paasForm.getPermission();

        List<OptionalRangeEntity> list = null;

        try {
            list = JSONArray.parseArray(permission, OptionalRangeEntity.class);
        } catch (Exception e) {

        }
        list = list == null ? new ArrayList<>() : list;

        TemplatePermissionVO templatePermissionVO = new TemplatePermissionVO();
        templatePermissionVO.setList(list);

        return templatePermissionVO;
    }

    @Override
    public BaseVO setTemplatePermission(TemplatePermissionSetDTO templatePermissionSetDTO) throws XbbException {
        String corpid = templatePermissionSetDTO.getCorpid();
        Long formId = templatePermissionSetDTO.getFormId();
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        //设置前读取旧的
        String key = "name";
        String permissionOld = commonHelp.changeArray2String(paasFormEntityExt.getPermission(), key);
        paasFormEntityExt.setPermission(JSON.toJSONString(templatePermissionSetDTO.getList()));
        paasFormModel.update(paasFormEntityExt);

        String permissionNew = commonHelp.changeArray2String(paasFormEntityExt.getPermission(), key);
        if (!Objects.equals(permissionOld, permissionNew)) {
            //有变更，插入日志
            String userName = templatePermissionSetDTO.getLoginUserName();
            String formName = paasFormEntityExt.getName();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_PERMISSION), userName, formName, permissionOld, permissionNew);
            mongoLogHelp.buildLog(corpid, templatePermissionSetDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_FORM, OperateTypeEnum.EDIT, formId.toString(), formName, memo, templatePermissionSetDTO.getHttpHeader());
        }
        return new BaseVO();
    }

    @Override
    public BaseVO changeEnable(TemplateChangeDTO templateChangeDTO) throws XbbException{
        Boolean isMulti = RedundantTemplateTypeEnum.isMultiTemplate(templateChangeDTO.getBusinessType());
        String corpid = templateChangeDTO.getCorpid();
        Long formId = templateChangeDTO.getFormId();
        Integer businessType = templateChangeDTO.getBusinessType();
        if (isMulti){
            Boolean enable = templateChangeDTO.getEnable();
            Map<String,Object> map = BeanUtil.convertBean2Map(templateChangeDTO,true);
            map.put("enable",1);
            map.put("negId",formId);
            map.put("del",0);
            Integer count = paasFormModel.getEntitysCount(map);
            //TODO haibin.zhang errcode
            if (!enable && count == 0){
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350007);
            }
        }
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId,corpid);
        // 记录日志
        String memo;
        OperateTypeEnum operateType;
        String userName = templateChangeDTO.getLoginUserName();
        String formName = paasFormEntityExt.getName();
        if (isMulti){
            boolean enable = templateChangeDTO.getEnable();
            paasFormEntityExt.setEnable(enable ? 1 : 0);
            paasFormModel.update(paasFormEntityExt);
            paasFormExplainModel.updateByFormId(paasFormEntityExt.getId(), corpid, enable ? 1 : 0);
            if (enable) {
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_FORM_ENABLE), userName, formName);
                operateType = OperateTypeEnum.ENABLE;
            } else {
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_FORM_CLOSE), userName, formName);
                operateType = OperateTypeEnum.CLOSE;
            }
        }else {
            Map<String,Object> map = BeanUtil.convertBean2Map(templateChangeDTO,true);
            map.put("enable",1);
            List<PaasFormEntityExt> paasFormEntityExtList = paasFormModel.list(map);
            if (!paasFormEntityExtList.isEmpty()){
                PaasFormEntityExt enablePaasFormEntityExt = paasFormEntityExtList.get(0);
                enablePaasFormEntityExt.setEnable(0);
                paasFormModel.update(enablePaasFormEntityExt);
                paasFormExplainModel.updateByFormId(enablePaasFormEntityExt.getId(), corpid, 0);
            }
            paasFormEntityExt.setEnable(1);
            paasFormModel.update(paasFormEntityExt);
            paasFormExplainModel.updateByFormId(paasFormEntityExt.getId(), corpid, 1);
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_FORM_ENABLE), userName, formName);
            operateType = OperateTypeEnum.ENABLE;
        }
        mongoLogHelp.buildLog(corpid, templateChangeDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_FORM, operateType, formId.toString(), formName, memo, templateChangeDTO.getHttpHeader());
        return new BaseVO();
    }

    @Override
    public CompanyVO getCompanyConfig(TemplateDTO templateDTO) throws XbbException{
        Integer businessType = templateDTO.getSubBusinessType();
        List<TemplateConfigGroupEnum> templateConfigGroupEnumList = TemplateConfigGroupEnum.getByBusinessType(businessType);
        List<CompanyPojo> companyPojoList = new ArrayList<>();
        List<String> aliasList = TemplateCompanyConfigEnum.getByBusinessType(businessType);
        Map<String,String> valueMap;
        if(aliasList.isEmpty()){
            valueMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }else {
            valueMap = companyConfigModel.getConfigValueMap(templateDTO.getCorpid(),aliasList);
        }
        for (TemplateConfigGroupEnum configGroupEnum : templateConfigGroupEnumList){
            List<FieldAttrEntity> fieldAttrEntityList = new ArrayList<>();
            List<TemplateCompanyConfigEnum> companyConfigEnumList = TemplateCompanyConfigEnum.getByGroupCode(configGroupEnum.getCode());
            for (TemplateCompanyConfigEnum configEnum : companyConfigEnumList){
                FieldAttrEntity fieldAttrEntity = new FieldAttrEntity();
                if (Objects.equals(configEnum.getFieldType(), FieldTypeEnum.SWITCH.getType())){
                    fieldAttrEntity = fieldAttrHelp.getBaseSwitchFiledAttr();
                }else if (Objects.equals(configEnum.getFieldType(),FieldTypeEnum.COMBO.getType())){
                    fieldAttrEntity = fieldAttrHelp.getBaseCombFiledAttr(configEnum.getDefaultValue());
                }
                String alias = configEnum.getAlias();
                fieldAttrEntity.setAttr(alias);
                fieldAttrEntity.setAttrName(configEnum.getName());
                DefaultAttrPoJo defaultAttrPoJo = new DefaultAttrPoJo();
                defaultAttrPoJo.setDefaultValue(valueMap.getOrDefault(alias, "1"));
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
                fieldAttrEntityList.add(fieldAttrEntity);
            }
            CompanyPojo companyPojo = new CompanyPojo();
            companyPojo.setGroupName(configGroupEnum.getName());
            companyPojo.setSetList(fieldAttrEntityList);
            companyPojoList.add(companyPojo);
        }
        CompanyVO companyVO = new CompanyVO();
        companyVO.setConfigList(companyPojoList);
        return companyVO;
    }

    @Override
    public BaseVO setCompanyConfig(CompanySaveDTO companySaveDTO) throws XbbException {
        TemplateCompanyConfigEnum templateCompanyConfigEnum = TemplateCompanyConfigEnum.getByAlias(companySaveDTO.getConfigAlias());
        if (templateCompanyConfigEnum == null){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(templateCompanyConfigEnum.getAlias(),companySaveDTO.getCorpid());
        if (companyConfigEntity == null){
            companyConfigEntity = new CompanyConfigEntity();
            BeanUtil.copyProperties(companySaveDTO,companyConfigEntity);
            companyConfigModel.insert(companyConfigEntity);
        }else {
            companyConfigEntity.setConfigValue(companySaveDTO.getConfigValue());
            companyConfigModel.update(companyConfigEntity);
        }
        return new BaseVO();
    }

    @Override
    public EnableVO getEnableList(TemplateDTO templateDTO) throws XbbException {
        List<PaasFormEntityExt> paasFormEntityList;
        //工单要特殊处理，工单里面要选到客户和经销商的
        if (Objects.equals(templateDTO.getSourceBusinessType(),XbbRefTypeEnum.WORK_ORDER.getCode()) && (Objects.equals(templateDTO.getBusinessType(),XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(templateDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode()))){
            templateDTO.setDistributorMark(null);
        }
        if (Objects.equals(templateDTO.getSourceBusinessType(), XbbRefTypeEnum.REFUND_INSTOCK.getCode()) && (Objects.equals(templateDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(templateDTO.getBusinessType(), XbbRefTypeEnum.REFUND.getCode()))) {
            // 经销商关闭后不允许选到经销商表单
            PaasAppEntity distributorAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.DISTRIBUTOR.getAlias(), templateDTO.getCorpid());
            if (Objects.isNull(distributorAppEntity) || Objects.equals(distributorAppEntity.getEnable(), 0)) {
                paasFormEntityList = paasFormService.getEnableFormList(templateDTO.getLoginUser(), templateDTO.getBusinessType(), templateDTO.getAppId(), templateDTO.getDistributorMark());
            } else {
                paasFormEntityList = paasFormService.getEnableFormList(templateDTO.getLoginUser(), templateDTO.getBusinessType(), templateDTO.getAppId(), null);
            }
        } else {
            paasFormEntityList = paasFormService.getEnableFormList(templateDTO.getLoginUser(), templateDTO.getBusinessType(), templateDTO.getAppId(), templateDTO.getDistributorMark());
        }
        //权限校验
        paasFormService.removeByPermission(paasFormEntityList, templateDTO.getLoginUser());
        List<EnablePojo> enablePojoList = formatEnableList(paasFormEntityList);
        EnableVO enableVO = new EnableVO();
        enableVO.setFormList(enablePojoList);
        enableVO.setSaasMark(templateDTO.getSaasMark());
        enableVO.setBusinessType(templateDTO.getBusinessType());
        return enableVO;
    }

    @Override
    public EnableVO getAllEnableList(TemplateDTO templateDTO) throws XbbException {
        List<PaasFormEntityExt> paasFormEntityList = paasFormService.getEnableFormList(templateDTO.getLoginUser(), templateDTO.getBusinessType(), templateDTO.getAppId(), templateDTO.getDistributorMark());
        List<EnablePojo> enablePojoList = formatEnableList(paasFormEntityList);
        EnableVO enableVO = new EnableVO();
        enableVO.setFormList(enablePojoList);
        return enableVO;
    }

    @Override
    public EnableVO templateList(TemplateDTO templateDTO) throws XbbException {
        List<EnablePojo> enablePojoList;
        //对线索、客户、联系人的查重业务做单独处理
        Integer subBusinessType = templateDTO.getSubBusinessType();
        boolean recheckFlag = Objects.nonNull(subBusinessType) && (Objects.equals(XbbRefTypeEnum.CLUE_DUPLICATE.getCode(), subBusinessType) ||
                Objects.equals(XbbRefTypeEnum.CUSTOMER_DUPLICATE.getCode(), subBusinessType) ||
                Objects.equals(XbbRefTypeEnum.CONTACT_DUPLICATE.getCode(), subBusinessType));
        if (recheckFlag){
            templateDTO.setBusinessType(null);
        }
        Integer businessType = templateDTO.getBusinessType();
        if (Objects.equals(templateDTO.getSubBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
            enablePojoList = getWorkOrderTemplateList(templateDTO);
        } else if (Objects.equals(templateDTO.getSubBusinessType(), XbbRefTypeEnum.WORK_ORDER_ROB.getCode())) {
            enablePojoList = getRobWorkOrderTemplateList(templateDTO);
        } else if (Objects.equals(templateDTO.getSubBusinessType(), XbbRefTypeEnum.WORK_REPORT.getCode())){
            enablePojoList = getWorkReportTemplateList(templateDTO);
        } else if (Objects.equals(templateDTO.getSubBusinessType(), XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode())){
            enablePojoList = getMarketingActivityManagementTemplateList(templateDTO);
        } else if (Objects.equals(templateDTO.getSubBusinessType(), XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())){
            enablePojoList = getPromotionActivityManagementTemplateList(templateDTO);
        } else if (Objects.equals(templateDTO.getSubBusinessType(), XbbRefTypeEnum.WRITE_OFF_RECORD.getCode())){
            enablePojoList = getWriteOffRecordTemplateList(templateDTO);
        } else if (Objects.equals(templateDTO.getSubBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
            enablePojoList = getProductPriceTemplateList(templateDTO);
        }else if (Objects.equals(templateDTO.getSubBusinessType(), XbbRefTypeEnum.WAIT_OUTSTOCK.getCode()) && templateDTO.getMenuId() > BasicConstant.ZERO) {
            enablePojoList = getWaitOutstockTemplateList(templateDTO);
        }else if(Objects.equals(XbbRefTypeEnum.SMART_REPLENISHMENT.getCode(),templateDTO.getBusinessType())){
            enablePojoList = getSmartReplenishmentTemplateList(templateDTO);
        }else if (Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode())){
            enablePojoList=getWaitPurchaseTemplateList(templateDTO);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())) {
            enablePojoList = getKnowledgeTemplateList(templateDTO);
        }else {
            enablePojoList = getSaasTemplateList(templateDTO);
        }
        //查看是否启用多单位公司级配置
        CompanyConfigEntity configEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_MULTI_UNIT.getAlias(), templateDTO.getCorpid());
        EnableVO enableVO = new EnableVO();
        enableVO.setFormList(enablePojoList);
        enableVO.setBusinessType(templateDTO.getBusinessType());
        enableVO.setSaasMark(templateDTO.getSaasMark());
        if (Objects.nonNull(configEntity)){
            if (StockConstant.EXPORT_MULTI_UNIT_TYPE_LIST.contains(businessType)) {
                enableVO.setEnbaleMultiUnit(Integer.valueOf(configEntity.getConfigValue()));
            }
        }
        // 如果客户在导入白名单中，添加上带附件的字段导出下拉框
        boolean importWhiteCorpidList = fileImportExportHelp.isWhiteListByCorpidAndType(templateDTO.getCorpid(), "importWhiteCorpidList");
        if (importWhiteCorpidList) {
            enableVO.setIsFileImport(1);
        }
        return enableVO;
    }

    private List<EnablePojo> getWaitOutstockTemplateList(TemplateDTO templateDTO) throws XbbException{
        Integer subBusinessType = templateDTO.getSubBusinessType();
        List<PaasFormEntityExt> paasFormEntityList = new ArrayList<>();
        List<PaasFormEntityExt> distributorEntityList = new ArrayList<>();
        Integer businessType = 0;
        businessType = saasListHelp.getBusinessType(subBusinessType);
        //获取经销商模版
        distributorEntityList = paasFormService.getEnableFormList(templateDTO.getLoginUser(), businessType, null, DistributorMarkEnum.DISTRIBUTOR.getCode());
        //获取非经销商模版
        paasFormEntityList = paasFormService.getEnableFormList(templateDTO.getLoginUser(), businessType, null, DistributorMarkEnum.OTHER.getCode());
        paasFormEntityList.addAll(distributorEntityList);
        List<EnablePojo> enablePojoList = new ArrayList<>();
        //过滤掉权限校验
        paasFormService.removeByPermission(paasFormEntityList, templateDTO.getLoginUser());
        for (PaasFormEntityExt entityExt : paasFormEntityList){
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(entityExt.getAppId());
            enablePojo.setMenuId(entityExt.getMenuId());
            enablePojo.setFormId(entityExt.getId());
            enablePojo.setFormName(entityExt.getName());
            enablePojo.setBusinessType(entityExt.getBusinessType());
            enablePojo.setDistributorMark(entityExt.getDistributorMark());
            enablePojoList.add(enablePojo);
        }
        templateDTO.setBusinessType(businessType);
        return enablePojoList;
    }

    private List<EnablePojo> getKnowledgeTemplateList(TemplateDTO templateDTO) {
        Integer subBusinessType = templateDTO.getSubBusinessType();
        List<EnablePojo> enablePojoList = new ArrayList<>();
        EnablePojo enablePojo = new EnablePojo();
        enablePojo.setAppId(templateDTO.getAppId());
        enablePojo.setMenuId(templateDTO.getMenuId());
        enablePojo.setFormId(0L);
        enablePojo.setBusinessType(subBusinessType);
        //enablePojo.setFormName();
        enablePojoList.add(enablePojo);
        templateDTO.setBusinessType(subBusinessType);
        return enablePojoList;
    }

    private List<EnablePojo> getWriteOffRecordTemplateList(TemplateDTO templateDTO) {
        Integer subBusinessType = templateDTO.getSubBusinessType();
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode(),templateDTO.getCorpid(), DistributorMarkEnum.DISTRIBUTOR.getCode(),null);
        List<EnablePojo> enablePojoList = new ArrayList<>();
        EnablePojo enablePojo = new EnablePojo();
        enablePojo.setAppId(paasFormEntityExt.getAppId());
        enablePojo.setMenuId(paasFormEntityExt.getMenuId());
        enablePojo.setFormId(paasFormEntityExt.getId());
        enablePojo.setBusinessType(subBusinessType);
        enablePojoList.add(enablePojo);
        templateDTO.setBusinessType(subBusinessType);
        return enablePojoList;
    }

    private List<EnablePojo> getPromotionActivityManagementTemplateList(TemplateDTO templateDTO) {
        Integer subBusinessType = templateDTO.getSubBusinessType();
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode(),templateDTO.getCorpid(), DistributorMarkEnum.DISTRIBUTOR.getCode(),null);
        List<EnablePojo> enablePojoList = new ArrayList<>();
        EnablePojo enablePojo = new EnablePojo();
        enablePojo.setAppId(paasFormEntityExt.getAppId());
        enablePojo.setMenuId(paasFormEntityExt.getMenuId());
        enablePojo.setFormId(paasFormEntityExt.getId());
        enablePojo.setFormName(ListGroupEnum.PROMOTION_GOODS.getName());
        enablePojo.setBusinessType(subBusinessType);
        enablePojoList.add(enablePojo);
        templateDTO.setBusinessType(subBusinessType);
        return enablePojoList;
    }

    private List<EnablePojo> getProductPriceTemplateList(TemplateDTO templateDTO) {
        Integer subBusinessType = templateDTO.getSubBusinessType();

        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode(), templateDTO.getCorpid(), DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        List<EnablePojo> enablePojoList = new ArrayList<>();
        EnablePojo enablePojo = new EnablePojo();
        enablePojo.setAppId(paasFormEntityExt.getAppId());
        enablePojo.setMenuId(paasFormEntityExt.getMenuId());
        enablePojo.setFormId(paasFormEntityExt.getId());
        enablePojo.setBusinessType(subBusinessType);
        enablePojoList.add(enablePojo);
        templateDTO.setBusinessType(subBusinessType);
        return enablePojoList;
    }

    private List<EnablePojo> getSmartReplenishmentTemplateList(TemplateDTO templateDTO) {
        Integer subBusinessType = templateDTO.getSubBusinessType();

        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PRODUCT.getCode(), templateDTO.getCorpid(), DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        List<EnablePojo> enablePojoList = new ArrayList<>();
        EnablePojo enablePojo = new EnablePojo();
        enablePojo.setAppId(paasFormEntityExt.getAppId());
        enablePojo.setMenuId(paasFormEntityExt.getMenuId());
        enablePojo.setFormId(paasFormEntityExt.getId());
        enablePojo.setBusinessType(subBusinessType);
        enablePojoList.add(enablePojo);
        templateDTO.setBusinessType(subBusinessType);
        return enablePojoList;
    }

    private List<EnablePojo> getWaitPurchaseTemplateList(TemplateDTO templateDTO) {
        Integer subBusinessType = templateDTO.getSubBusinessType();
        List<PaasFormEntityExt> paasFormEntityList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("businessType", XbbRefTypeEnum.CONTRACT.getCode());
        param.put("corpid", templateDTO.getCorpid());
        param.put("del",DelEnum.NORMAL.getDel());
        param.put("distributorMark",DistributorMarkEnum.OTHER.getCode());
        param.put("orderByStr","sort");
        List<PaasFormEntityExt> formEntitys = paasFormModel.getByBusinessTypes(param);
        PaasFormEntityExt contractForm;
        if (CollectionUtils.isNotEmpty(formEntitys)){
            contractForm = formEntitys.get(0);
            contractForm.setName(I18nMessageUtil.getMessage(I18nStringConstant.OUT_OF_STOCK_CONTRACT) + (Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode()) ? I18nMessageUtil.getMessage(I18nStringConstant.PURCHASE) : I18nMessageUtil.getMessage(I18nStringConstant.PRODUCE)));
            paasFormEntityList.add(contractForm);
        }
        PaasFormEntityExt productForm = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),templateDTO.getCorpid());
        productForm.setName(I18nMessageUtil.getMessage(I18nStringConstant.OUT_OF_STOCK_PRODUCT)  + (Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode()) ? I18nMessageUtil.getMessage(I18nStringConstant.PURCHASE) : I18nMessageUtil.getMessage(I18nStringConstant.PRODUCE)));
        paasFormEntityList.add(productForm);
        // 过滤没使用权限的表单
        paasFormService.removeByPermission(paasFormEntityList, templateDTO.getLoginUser());
        List<EnablePojo> enablePojoList = new ArrayList<>();
        for (PaasFormEntityExt entityExt : paasFormEntityList){
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(entityExt.getAppId());
            enablePojo.setMenuId(entityExt.getMenuId());
            enablePojo.setFormId(entityExt.getId());
            enablePojo.setFormName(entityExt.getName());
            enablePojo.setBusinessType(entityExt.getBusinessType());
            enablePojo.setDistributorMark(entityExt.getDistributorMark());
            enablePojoList.add(enablePojo);
        }
        return enablePojoList;
    }


    private List<EnablePojo> getMarketingActivityManagementTemplateList(TemplateDTO templateDTO) throws XbbException {
        Integer subBusinessType = templateDTO.getSubBusinessType();

        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode(),templateDTO.getCorpid(), DistributorMarkEnum.DISTRIBUTOR.getCode(),null);
        List<EnablePojo> enablePojoList = new ArrayList<>();
        EnablePojo enablePojo = new EnablePojo();
        enablePojo.setAppId(paasFormEntityExt.getAppId());
        enablePojo.setMenuId(paasFormEntityExt.getMenuId());
        enablePojo.setFormId(paasFormEntityExt.getId());
        enablePojo.setFormName(ListGroupEnum.COUPON.getName());
        enablePojo.setBusinessType(subBusinessType);
        enablePojoList.add(enablePojo);
        templateDTO.setBusinessType(subBusinessType);
        return enablePojoList;
    }


    @Override
    public List<EnablePojo> getSaasTemplateList(TemplateDTO templateDTO) throws XbbException {

        PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
        paasFormEntityExt.setAppId(templateDTO.getAppId());
        paasFormEntityExt.setMenuId(templateDTO.getMenuId());
        paasFormEntityExt.setSaasMark(templateDTO.getSaasMark());
        paasFormEntityExt.setDistributorMark(templateDTO.getDistributorMark());
        List<EnablePojo> list = formTemplateModel.getSaasTemplateList(templateDTO.getCorpid(), paasFormEntityExt,  templateDTO.getSubBusinessType(), templateDTO.getLoginUser());
        // 之前这边也有个set方法
        templateDTO.setBusinessType(FormTemplateModelImpl.changeBusinessType(templateDTO.getSubBusinessType()));
        return list;
    }

    @Override
    public EnableVO  templateListPrint(TemplateDTO templateDTO) throws XbbException {
        WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByTemplateId(templateDTO.getMenuId(), templateDTO.getCorpid());
        List<EnablePojo> enablePojoList = new ArrayList<>();
        if (Objects.nonNull(workOrderFormEntityExt)){
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(workOrderFormEntityExt.getAppId());
            enablePojo.setMenuId(workOrderFormEntityExt.getTemplateId());
            enablePojo.setFormId(workOrderFormEntityExt.getId());
            enablePojo.setFormName(workOrderFormEntityExt.getName());
            enablePojo.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            enablePojoList.add(enablePojo);
        }
        EnableVO enableVO = new EnableVO();
        enableVO.setFormList(enablePojoList);
        enableVO.setBusinessType(templateDTO.getBusinessType());
        enableVO.setSaasMark(templateDTO.getSaasMark());
        return enableVO;
    }

    @Override
    public BaseVO checkNum(TemplateDTO templateDTO) throws XbbException {
        CompanyConfigFindDTO companyConfigFindDTO = new CompanyConfigFindDTO();
        companyConfigFindDTO.setConfigAlias(CompanyConfigEnum.SYSTEM_FORM_LIMIT_NUM.getAlias());
        companyConfigFindDTO.setCorpid(templateDTO.getCorpid());
        CompanyConfigFindVO companyConfig = companyConfigService.findCompanyConfigByRedis(companyConfigFindDTO);
        Integer formMaxNum = Objects.isNull(companyConfig.getConfigValue()) ? 6 : Integer.valueOf(companyConfig.getConfigValue());
        if (Objects.equals(templateDTO.getBusinessType(),XbbRefTypeEnum.WORK_ORDER_V2.getCode())) {
            formMaxNum = BasicConstant.WORK_ORDER_V2_TEMPLATE_NUM;
        }
        Map<String, Object> param = new HashMap<>(4);
        param.put(StringConstant.CORPID, templateDTO.getCorpid());
        param.put(StringConstant.BUSINESS_TYPE, templateDTO.getBusinessType());
        param.put(StringConstant.DEL,DelEnum.NORMAL.getDel());
        param.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        Integer count = paasFormModel.getEntitysCount(param);
        // 工单v2最多50个限制
        // 无配置，最多6个
        // 有配置则取配置的数值
        if (count >= formMaxNum) {
            throw new XbbException(ErrorCodeEnum.API_ERROR_500022, ErrorCodeEnum.API_ERROR_500022.getMsg(), formMaxNum);
        }
        return new BaseVO();
    }

    /**
     * Description: 修改表单排序值
     *
     * @param listTemplateSortDTO
     * @return com.xbongbong.paas.toolbox.wrap.BaseVO
     * @author 秦春阳
     * @date 2020/7/7 15:49
     * @since v1.0
     */
    @Override
    public BaseVO updateTemplateSort(ListTemplateSortDTO listTemplateSortDTO) throws IllegalAccessException, XbbException, InstantiationException {
        //取出表单数据
        List<PaasFormEntity> paasFormEntityList = new ArrayList<>();
        BeanUtil.copyPropertiesList(listTemplateSortDTO.getFormList(), paasFormEntityList, PaasFormEntity.class);
        paasFormModel.updateBatch(paasFormEntityList, listTemplateSortDTO.getCorpid());
        return new BaseVO();
    }


    /**
     * Description: 根据工单权限设置获取工单启用的模板列表
     * @param templateDTO
     * @return java.util.List<com.xbongbong.pro.template.pojo.EnablePojo>
     * @author 魏荣杰
     * @date 2019/5/16 15:49
     * @since v1.0
     */
    private List<EnablePojo> getWorkOrderTemplateList(TemplateDTO templateDTO) {
        List<WorkOrderFormEntity> workOrderFormEntityList = workOrderFormService.getTemplateWithPermission(templateDTO.getLoginUser(), templateDTO.getAppId(), null);
        List<EnablePojo> enablePojoList = new ArrayList<>();
        for (WorkOrderFormEntity entityExt : workOrderFormEntityList){
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(entityExt.getAppId());
            enablePojo.setMenuId(entityExt.getMenuId());
            enablePojo.setFormId(entityExt.getId());
            enablePojo.setFormName(entityExt.getName());
            enablePojo.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            enablePojoList.add(enablePojo);
        }
        if (workOrderFormEntityList.size() > 1) {
            WorkOrderFormEntity workOrderFormEntity = workOrderFormEntityList.get(0);
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(workOrderFormEntity.getAppId());
            enablePojo.setMenuId(workOrderFormEntity.getMenuId());
            enablePojo.setFormId(0L);
            enablePojo.setFormName(I18nMessageUtil.getMessage(CommonConstant.ALL));
            enablePojo.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            enablePojoList.add(0, enablePojo);
        }

        templateDTO.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
        return enablePojoList;
    }

    /**
     * Description: 根据工作报告权限设置获取工作报告启用的模板列表
     * @param templateDTO
     * @return java.util.List<com.xbongbong.pro.template.pojo.EnablePojo>
     * @author cyy
     * @date
     * @since v1.0
     */
    private List<EnablePojo> getWorkReportTemplateList(TemplateDTO templateDTO) throws XbbException{
        List<PaasFormEntityExt> paasFormEntityList = paasFormService.getEnableFormList(templateDTO.getLoginUser(),XbbRefTypeEnum.WORK_REPORT.getCode(),templateDTO.getAppId(), templateDTO.getDistributorMark());
        List<EnablePojo> enablePojoList = new ArrayList<>();
        for (PaasFormEntityExt entityExt : paasFormEntityList){
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(entityExt.getAppId());
            enablePojo.setMenuId(entityExt.getMenuId());
            enablePojo.setFormId(entityExt.getId());
            enablePojo.setFormName(entityExt.getName());
            // 多模板通过formId来区分是日报 周报还是月报
            enablePojo.setBusinessType(XbbRefTypeEnum.WORK_REPORT.getCode());
            enablePojoList.add(enablePojo);
        }
        if (paasFormEntityList.size() > 1) {
            PaasFormEntityExt paasFormEntity = paasFormEntityList.get(0);
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(paasFormEntity.getAppId());
            enablePojo.setMenuId(paasFormEntity.getMenuId());
            enablePojo.setFormId(0L);
            enablePojo.setFormName(I18nMessageUtil.getMessage(CommonConstant.ALL));
            enablePojo.setBusinessType(XbbRefTypeEnum.WORK_REPORT.getCode());
            enablePojoList.add(0, enablePojo);
        }

        templateDTO.setBusinessType(XbbRefTypeEnum.WORK_REPORT.getCode());
        return enablePojoList;
    }


    /**
     * Description: 根据工单权限设置获取工单启用的模板列表(用于抢单列表，过滤自由流程模板数据)
     * @param templateDTO
     * @return java.util.List<com.xbongbong.pro.template.pojo.EnablePojo>
     * @throws
     * @author 魏荣杰
     * @date 2019/5/16 15:55
     * @since
     */
    private List<EnablePojo> getRobWorkOrderTemplateList(TemplateDTO templateDTO) {
        List<WorkOrderFormEntity> workOrderFormEntityList = workOrderFormService.getTemplateWithPermission(templateDTO.getLoginUser(), templateDTO.getAppId(), 0);
        List<EnablePojo> enablePojoList = new ArrayList<>();
        for (WorkOrderFormEntity entityExt : workOrderFormEntityList){
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(entityExt.getAppId());
            enablePojo.setMenuId(entityExt.getMenuId());
            enablePojo.setFormId(entityExt.getId());
            enablePojo.setFormName(entityExt.getName());
            enablePojo.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            enablePojoList.add(enablePojo);
        }
        if (workOrderFormEntityList.size() > 1) {
            WorkOrderFormEntity workOrderFormEntity = workOrderFormEntityList.get(0);
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(workOrderFormEntity.getAppId());
            enablePojo.setMenuId(workOrderFormEntity.getMenuId());
            enablePojo.setFormId(0L);
            enablePojo.setFormName(I18nMessageUtil.getMessage(CommonConstant.ALL));
            enablePojo.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            enablePojoList.add(0, enablePojo);
        }
        templateDTO.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
        return enablePojoList;
    }

    /**
     * 格式化模板返回参数
     * @param enableFormList
     * @return java.util.List<com.xbongbong.pro.template.pojo.EnablePojo>
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private List<EnablePojo> formatEnableList(List<PaasFormEntityExt> enableFormList) {
        List<EnablePojo> enablePojoList = new ArrayList<>();
        for (PaasFormEntityExt entityExt : enableFormList) {
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setMenuId(entityExt.getMenuId());
            enablePojo.setFormId(entityExt.getId());
            enablePojo.setFormName(entityExt.getName());
            enablePojo.setAppId(entityExt.getAppId());
            enablePojo.setDistributorMark(entityExt.getDistributorMark());
            enablePojo.setBusinessType(entityExt.getBusinessType());
            enablePojoList.add(enablePojo);
        }
        return enablePojoList;
    }
}
